﻿using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace NIF.MobileActors.Hosts
{
    public class AssemblyManager
    {
        public byte[] GetRawAssembly(string key)
        {
            if (!IsLocalAssembly(key))
                return null;
            return actorAssemblies[key];
        }        

        public bool IsLocalAssembly(string key)
        {
            //if (actorAssemblies.ContainsKey(key))
            //{
            //    Assembly asm = Assembly.Load(key);
            //}
            return actorAssemblies.ContainsKey(key);
        }

        public void Add(string key, byte[] codeData)
        {
            if (!IsLocalAssembly(key))
            {
                using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + '\\' + key + ".asm", FileMode.OpenOrCreate))
                {
                    fs.Write(codeData, 0, codeData.Length);
                    fs.Close();
                }
            }
            actorAssemblies.AddOrUpdate(key, codeData, (k,v) => v);
        }



        private ConcurrentDictionary<string, byte[]> actorAssemblies
            = new ConcurrentDictionary<string, byte[]>();

        public static AssemblyManager Instance
        {
            get
            {
                if (m_instance == null)
                {
                    m_instance = new AssemblyManager();
                }
                return m_instance;
            }
        }
        private static AssemblyManager m_instance = null;
    }
}
